using Modding;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace ExampleMods
{
    public class HealthStatus : UnityEngine.MonoBehaviour
    {
        public int Id { get; set; }

        public string Name { get; private set; }

        public float Max { get; private set; } = 100;

        public float Current { get; private set; }

        /// <summary>
        /// 最近一次的实时血量
        /// </summary>
        public float Prev { get; private set; }

        /// <summary>
        /// 动态变化的血量,扣血效果
        /// </summary>
        public float Delta { get; set; }

        /// <summary>
        /// 最近一次变更血量的时间
        /// </summary>
        public float Tick { get; set; } = Time.time;

        public float BeginTime { get; internal set; }

        public float BeginDelta { get; internal set; }

        /// <summary>
        /// 1秒内伤害求和
        /// </summary>
        public float DamageInOne { get; internal set; }

        public float DamageTick { get; internal set; }

        GameObject enemy;
        HealthManager health;

        internal void Init(GameObject enemy, HealthManager health)
        {
            this.health = health;
            this.enemy = enemy;
            //   var cs = enemy.GetComponents<object>();
            //   var msg = string.Join(" | ", cs.Select(p => p.ToString()));
            //   Modding.Logger.Log($" components: {msg}");
            this.Current = this.Prev = this.Delta = this.Max = health.hp;
            this.DamageInOne = 0;
            this.Name = enemy.name;
        }

        void OnDestroy()
        {
            Invalidate();
        }

        void FixedUpdate()
        {
            Invalidate();
        }

        private void Invalidate()
        {
            Current = Mathf.Max(0, health?.hp ?? 0);
            if (Current != Prev)
            {
                this.Tick = Time.time;
                this.BeginTime = Time.time;
                this.BeginDelta = this.Delta;
                if (Time.time - this.DamageTick > 1)
                {
                    this.DamageTick = Time.time;
                    this.DamageInOne = Prev - Current;
                }
                else
                {
                    this.DamageInOne += Prev - Current;
                }
                HealthPoint.Attack(this);
            }
            Prev = Current;
        }

    }
}
